<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Waste\Controllers;


use App\Eloquent\Area;
use App\Eloquent\City;
use App\Eloquent\Province;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\User;
use App\Eloquent\Ygt\WasteBuyer;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class IndexController extends Controller
{
    public $userId        = 25;
    public function index(){}
    public function lists()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $title              = request('keyword','');
        $level              = request('level',0);
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = [
            'ygt_waste_buyer.company_id'=>$companyId,
        ];
        if($title)
        {
            $where['ygt_waste_buyer.title'] = ['like','%'.$title.'%'];
        }
        if($level>0)
        {
            $where['ygt_waste_buyer.level'] = $level;
        }
        $collection         = WasteBuyer::getJoinList($where,$limit='',$offset='',$type=1,$orderby=['ygt_waste_buyer.id','desc']);
        $levelArr           = WasteBuyer::getLevelListByType(2);
        foreach($collection as $key=>$val)
        {
            $collection[$key]->address_address  = $val->province_name.$val->city_name.$val->area_name.$val->address;

            $valLevel       = $val->level;
            $levelName      = isset($levelArr[$valLevel]) ? $levelArr[$valLevel] : '';
            $collection[$key]->level_name       = $levelName;

            $valImgUrl      = $val->img_url;
            $imgPath        = Func::getImgUrlHttp($valImgUrl);
            $collection[$key]->img_path          = $imgPath;
            $collection[$key]->total_money      = '总: ';
            $collection[$key]->pay_money        = '应收: ';
        }
        $lists              = Func::getLetterList($collection);
        $result             = ['lists'=>$lists];
        return $lists;
    }
    public function edit()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $companyId              = $userInfo->company_id;
        $id                     = request('id',0);//有值时编辑,无值是添加
        $isEdit                 = $id == 0 ? 0 : 1;
        if($isEdit == 0){
            //添加收品单位
            $contactMobile      = request('contact_mobile',0);
            $regMobile          = request('reg_mobile',0);
            $title              = request('title','');
            if(!$title)
            {
                xThrow( ERR_PARAMETER,'收品单位名称未填写');
            }
            if(!$regMobile)
            {
                xThrow( ERR_PARAMETER,'联系人手机未填写');
            }
            //判断收品单位对应的账号是否存在
            $registerResult     = User::registerByType($regMobile,$title,3);
            $registerStatus     = $registerResult['status'];
            $registerUserId     = $registerResult['user_id'];
            $registerMessage    = $registerResult['message'];
            //$registerStatus 0失败,1不存在插入成功,2已存在取值成功
            if($registerStatus == 1){
                //若是新注册的则需插入的员工表,,注意这时的厂id是特殊的
                $defaultArr             = config('ygt.waste_buyer_arr');
                $registerCompanyId      = $defaultArr['company_id'];
                $privilegeId            = $defaultArr['privilege_id'];
                $departmentUserData     = [
                    'user_id'=>$registerUserId,
                    'company_id'=>$registerCompanyId,
                    'privilege_id'=>$privilegeId,
                    'mobile'=>$regMobile,
                    'truename'=>$title,
                ];
                DepartmentUser::insertOneData( $departmentUserData );
            }else if($registerStatus == 2){
                //暂时不需要做处理
            }else{
                xThrow(ERR_PARAMETER, $registerMessage);
            }
            $tableUserId            = $registerUserId;
            $addUserId              = $userId;
            $resultMessageArr       = ['success'=>'添加成功','error'=>'添加失败'];
        }else{
            //编辑收品单位
            $where          = ['id'=>$id];
            $info           = WasteBuyer::getInfo($where);
            if(!$info)
            {
                xThrow(ERR_UNKNOWN,'该信息不存在');
            }
            $tableUserId        = $info->user_id;
            $addUserId          = $info->add_user_id;
            $regMobile          = $info->reg_mobile;
            $resultMessageArr   = ['success'=>'编辑成功','error'=>'编辑失败'];
        }
        $data               = request()->all();
        //省市县
        $provinceName       = $cityName = $areaName = '';
        if(isset($data['province_id']))
        {
            $provinceId     = $data['province_id'];
            $where          = ['provinceID'=>$provinceId];
            $collection     = Province::where($where)->first();
            if($collection)
            {
                $provinceName   = $collection->province;
            }
        }
        if(isset($data['city_id']))
        {
            $cityId         = $data['city_id'];
            $where          = ['cityID'=>$cityId];
            $collection     = City::where($where)->first();
            if($collection)
            {
                $cityName       = $collection->city;
            }
        }
        if(isset($data['area_id']))
        {
            $areaId         = $data['area_id'];
            $where          = ['areaID'=>$areaId];
            $collection     = Area::where($where)->first();
            if($collection)
            {
                $areaName       = $collection->area;
            }
        }
        $data['province_name']  = $provinceName;
        $data['city_name']      = $cityName;
        $data['area_name']      = $areaName;
        //首字母
        $firstLetter        = '#';
        if(isset($data['title']))
        {
            $title              = $data['title'];
            $pinyin             = app('pinyin')->abbr($title);
            $firstLetter        = strtoupper(substr($pinyin,0,1));
            $letterAll          = [];
            for($i=65;$i<91;$i++){
                $letterAll[]    = chr($i);
            }
            if(!in_Array($firstLetter,$letterAll))
            {
                $firstLetter    = '#';
            }
        }
        $data['first_letter']   = $firstLetter;
        //其它信息
        $data['company_id']     = $companyId;
        $data['user_id']        = $tableUserId;
        $data['add_user_id']    = $addUserId;
        $data['reg_mobile']     = $regMobile;

        $fieldList              = WasteBuyer::$tableFieldList;
        $tableData              = WasteBuyer::setDataByTableField($data,$fieldList);
        $tableDataCheckResult   = WasteBuyer::checkDataByTableField($tableData,$fieldList);
        if($tableDataCheckResult !== true)
        {
            xThrow(ERR_PARAMETER, $tableDataCheckResult);
        }
        $relationId             = WasteBuyer::editData($tableData,'id');
        if($relationId===false)
        {
            xThrow(ERR_UNKNOWN,$resultMessageArr['error']);
        }
        return ['message'=>$resultMessageArr['success']];
    }
    public function level()
    {
        $result         = WasteBuyer::getLevelListByType();
        return $result;
    }
    public function detail()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $requestId          = request('id',0);
        if(!$userInfo || !$requestId)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $companyId          = $userInfo->company_id;
        $where              = [
            'ygt_waste_buyer.company_id'=>$companyId,
            'ygt_waste_buyer.id'=>$requestId,
        ];
        $info               = WasteBuyer::getJoinInfo($where);
        if(!$info)
        {
            xThrow( ERR_PARAMETER,'信息出错');
        }
        $levelArr           = WasteBuyer::getLevelListByType(2);
        $infoLevel          = $info->level;
        $levelName          = isset($levelArr[$infoLevel]) ? $levelArr[$infoLevel] : '';
        $info->level_name  = $levelName;
        $infoImgUrl         = $info->img_url;
        $imgPath            = Func::getImgUrlHttp($infoImgUrl);
        $info->img_path    = $imgPath;
        $info->address_address  = $info->province_name.$info->city_name.$info->area_name.$info->address;
        $infoArr            = $info->toArray();
        return $infoArr;
    }


    //获取工单废料详情
    public function getOrderWasteDetail()
    {

        //调整为分批提交记录ID,zhuyujun,20181120
        $orderProcessMaterialSubmitId = request('order_process_id');//17
        $orderProcessMaterialSubmitRow = \App\Eloquent\Ygt\OrderProcessMaterialSubmit::where(['id'=>$orderProcessMaterialSubmitId])->first();
        $orderProcessId = $orderProcessMaterialSubmitRow['order_process_id'];//3471

        $orderProcessRow =  \App\Eloquent\Ygt\OrderProcess::where(['id'=>$orderProcessId])->first();
        //1022
        $orderInfo = \App\Eloquent\Ygt\Order::where(['id'=>$orderProcessRow['order_id']])->first();


        //获取工序类型名称
        $orderTypeTitle = \App\Engine\OrderType::getOneValueById($orderInfo['order_type'], 'title');
        //双面彩印袋

        //处理图片数据
        $imgIdList = explode(',', $orderInfo['production_case_diagram']);
        $exampleImg = '';
        $imgNum = 0;
        foreach ($imgIdList as $imgId) {
            if (!trim($imgId)) {//过滤空格 图片id应该不会有0
                continue;
            }
            $imgNum++;
            if (!$exampleImg) {//取第一张图作为示例图
                $exampleImg = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($imgId);//示例图片
            }
        }

        $return['img_title'] = '共' . $imgNum . '张图片';//示例图文字提示


        //工单号、工单数量，交货日期
        $orderInfo['order_title'];
        $orderInfo['finished_date'];

        $orderNum = '';
        if($orderInfo['product_num']){
            $tmpArr = explode(',',$orderInfo['product_num']);
            if( (count($tmpArr) == 2) && $tmpArr[0]){
                $orderNum = $tmpArr[0].$tmpArr[1];
            }
        }


        //获取对应废品信息
        $orderProcessWasteList = \App\Eloquent\Ygt\OrderProcessWaste::where(['order_process_material_submit_id'=>$orderProcessMaterialSubmitId])->get();

        //获取工序信息
        $processTitle = \App\Eloquent\Ygt\Process::getOneValueById($orderProcessRow['process_type'], 'title');

        $materialWasteList = $processWasteList = [];
        $materialWasteList['title'] = $processTitle.'材料废品';
        $materialWasteList['data'] = [];
        $processWasteList['title'] = $processTitle.'工序废品';
        $processWasteList['data'] = [];

        foreach ($orderProcessWasteList as $orderProcessWasteRow){
            $relateType = $orderProcessWasteRow['relate_type'];
            if($relateType == 1){//材料废品
                //获取材料信息
                $materialId = $orderProcessWasteRow['relate_id'];
                //echo $materialId.',';
                //获取材料信息
                $materialRowPre = \App\Eloquent\Ygt\Product::where(['id'=>$materialId])->first();
                if(!$materialRowPre){
                    continue;
                }

                $materialRow['id'] = $materialRowPre['id'];
                $materialRow['img_id'] = $materialRowPre['img_id'];
                $materialRow['seller_company_id'] = $materialRowPre['seller_company_id'];
                $materialRow['unit'] = $materialRowPre['unit'];
                $materialRow['product_name'] = $materialRowPre['product_name'];


                //追加材料自定义属性
                $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
                $where = ['product_id' => $materialRow['id']];
                $productFields = $ProductFieldsModel->getData($where,'','','',['id','asc']);
                $productFields = $productFields->map(function ($item) {
                    $data['field_name'] = $item->field_name;
                    $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);

                    $data['field_value'] = $item->$comumnName.$item['unit'];
                    return $data;
                });


                $fieldsList         = $productFields;
                $firstText = $secondText = $thirdText ='';
                if(!empty($fieldsList))
                {
                    if(isset($fieldsList[0]))
                    {
                        $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                    }
                    if(isset($fieldsList[1]))
                    {
                        $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                    }
                    if(isset($fieldsList[2]))
                    {
                        $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                    }
                }
                $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
                $materialRow['custom_fields']        = $fieldsList;
                $materialRow['first_text']           = $firstText;
                $materialRow['second_text']          = $secondText;
                $materialRow['third_text']           = $thirdText;
                $materialRow['custom_fields_text']   = $customFieldsText;
                $materialRow['custom_fields'] = $productFields;

                //追加材料图片地址
                $materialRow['img_url'] = '';
                if ($materialRow['img_id']) {
                    $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                }

                //供应商
                if(!$materialRow['seller_company_id']){
                    $materialRow['supllier_name'] = '本厂材料';
                }else{
                    $supllierRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$materialRow['seller_company_id']])->first();
                    if($supllierRow){
                        $materialRow['supllier_name'] = "供应商：".$supllierRow['title'];
                    }else{
                        $materialRow['supllier_name'] = '未知供应商';
                    }
                }

                //废品数量
                $materialRow['waste_num'] = $orderProcessWasteRow['number'].$materialRow['unit'];

                $materialWasteList['data'][] = $materialRow;

            }elseif($relateType == 2){//工序废品

                $processRow = [];
                //获取工序废品信息--废品名称
                $processWasteTitle = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$orderProcessWasteRow['relate_id']])->first();
                if($processWasteTitle){
                    $processWasteTitle = $processWasteTitle->title;
                }else{
                    //获取软删除数据
                    $processWasteTitle = \App\Eloquent\Ygt\OrdertypeProcessWaste::withTrashed()->where(['id'=>$orderProcessWasteRow['relate_id']])->first();
                    if($processWasteTitle){
                        $processWasteTitle = $processWasteTitle->title.'【已删除】';;
                    }else{
                        $processWasteTitle = '';
                    }
                }

                $processRow['id'] = $orderProcessWasteRow['relate_id'];
                $processRow['title'] = $processWasteTitle;
                $processRow['waste_num'] = $orderProcessWasteRow['number'].'kg';

                $processWasteList['data'][] = $processRow;
            }
        }

        $isHideButton = 0;
        //判断是否已入过库
        $tmpWasteWaterObj = \App\Eloquent\Ygt\WasteWater::where(['type'=>1,'relate_id'=>$orderProcessMaterialSubmitId])->first();
        if($tmpWasteWaterObj){
            $isHideButton = 1;
        }


        $detailList = [];
        if(!empty($materialWasteList)){
            $detailList[] = $materialWasteList;
        }


        $re = [
            'image_url' => $exampleImg,//示例图
            'img_title' => '共' . $imgNum . '张图片',//示例图文字提示
            'ordertype_title' => $orderTypeTitle,//工序类型名称
            'order_title' => '工单号:' . $orderInfo['order_title'],//工单号
            'order_num' => '工单数量:' . $orderNum,//工单数量
            'finish_date' => '交货日期:' . $orderInfo['finished_date'],//交货日期
            'order_process_id' => $orderProcessMaterialSubmitId,//工单工序ID,用于后续传值 改为新值
            'is_hide_button' => $isHideButton,//如果已入库隐藏按钮 1-隐藏 0-显示
            'material_waste_list' => $materialWasteList,//材料废品列表
            'process_waste_list' => $processWasteList,//工序废品列表

        ];//接口返回的值

        return $re;
    }

    //废品员确认废品（废品入库）
    public function orderWasteCheckin()
    {
        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        //新逻辑调整为分批提交记录ID zhuyujun 20181120
        $orderProcessMaterialSubmitId = request('order_process_id');

        //获取信息
        $orderProcessWasteList = \App\Eloquent\Ygt\OrderProcessWaste::where(['order_process_material_submit_id'=>$orderProcessMaterialSubmitId])->get();

        foreach ($orderProcessWasteList as $orderProcessWasteRow){
            //废品库存处理
            $relateType = $orderProcessWasteRow['relate_type'];
            $relateId = $orderProcessWasteRow['relate_id'];

            //获取废品名称
            $wasteName = '';
            if($relateType == 1){//材料
                $materialRow = \App\Eloquent\Ygt\Product::where(['id'=>$relateId])->first();
                if($materialRow){
                    $wasteName = $materialRow['product_name'];
                }

            }elseif($relateType == 2){//工序废品
                $ordertypeProcessWasteRow = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$relateId])->first();
                if(!$ordertypeProcessWasteRow){
                    $wasteName = $ordertypeProcessWasteRow['title'];
                }else{
                    //获取软删除数据
                    $processWasteTitle = \App\Eloquent\Ygt\OrdertypeProcessWaste::withTrashed()->where(['id'=>$relateId])->first();
                    if($processWasteTitle){
                        $wasteName = $processWasteTitle->title.'【已删除】';;
                    }
                }
            }


            $wasteObj = \App\Eloquent\Ygt\Waste::firstOrNew(['relate_type'=>$relateType,'relate_id'=>$relateId]);
            $wasteObj->waste_name = $wasteName;
            $wasteObj->relate_type = $relateType;
            $wasteObj->relate_id = $relateId;
            $wasteObj->number = $wasteObj->number + $orderProcessWasteRow['number'];
            $wasteObj->total_number = $wasteObj->total_number + $orderProcessWasteRow['number'];
            $wasteObj->company_id = $userInfo['company_id'];

            $wasteObj->save();


            //废品流水添加
            $wasteId = $wasteObj->id;

            //获取流水单位
            $unit = '';
            if($relateType == 1){
                $materialRow =  \App\Eloquent\Ygt\Product::where(['id'=>$relateId])->first();
                if($materialRow){
                    $unit = $materialRow->unit;
                }

            }else{
                $unit = 'kg';
            }

            $wasteWaterObj = \App\Eloquent\Ygt\WasteWater::firstOrNew(['id'=>'']);
            $tmpInsertRow = [
                'waste_id' => $wasteId,
                'type' => 1,//1-工单废料入库
                'relate_id' => $orderProcessWasteRow['order_process_material_submit_id'],
                'number' => $orderProcessWasteRow['number'],
                'unit' => $unit,
                'residual_number' => $wasteObj->number,
                'company_id' => $userInfo['company_id'],
                'uid' => $userId,
            ];

            $wasteWaterObj->fill($tmpInsertRow);
            $wasteWaterObj->save();
        }

        return '操作成功';
    }

    //废品员卖废品
    public function sellWasteSubmit()
    {
        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $wasteBuyerId = request('waste_buyer_id');
        $submitWasteList = request('waste_list');

        $wasterSellList = [];
        $wasteIds = [];
        if($submitWasteList){
            $submitWasteList = \GuzzleHttp\json_decode(htmlspecialchars_decode($submitWasteList), true);


            $wasterSellList['total_price'] = $wasterSellList['total_number'] = 0;
            $wasterSellList['list'] = [];
            foreach ($submitWasteList as $submitWasteRow){
                $wasteId = $submitWasteRow['waste_id'];
                $sellNum = $submitWasteRow['number'];
                $sellPrice = $submitWasteRow['price'];


                //卖出数量不能为0&&卖出单价不能为0
                if($sellNum == 0){
                    return [
                        'code' => 1,
                        'message' => '请填写卖出数量'
                    ];
                }

                if($sellPrice == 0){
                    return [
                        'code' => 1,
                        'message' => '请填写卖出单价'
                    ];
                }

                $wasteIds[] = $wasteId;

                //判断卖出是否符合要求
                $wasterRow = \App\Eloquent\Ygt\Waste::where(['id'=>$wasteId])->first();
                if(!$wasterRow){
                    continue;
                }



                if($sellNum > $wasterRow['number']){
                    return [
                        'code' => 1,
                        'message' => '卖出数量不能大于库存'
                    ];
                }

                $wasterSellList['total_price'] += $sellNum*$sellPrice;
                $wasterSellList['total_number'] ++;
                $wasterSellList['list'][] = $submitWasteRow;

            }
        }

        //数据保存
        if(!empty($wasterSellList)){
            $wasteSellObj = \App\Eloquent\Ygt\WasteSell::firstOrNew(['id'=>'']);

            ////生成废品卖出记录编号
            $wasteNumber = '';

            //获取是当天的第几单
            $dayStartTime = strtotime(date('Ymd'));
            $intradayCount = \App\Eloquent\Ygt\WasteSell::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();

            $titleIndex = '';
            $intradayCount++;
            if ($intradayCount < 10) {
                $titleIndex = sprintf('0%d', $intradayCount);
            } else {
                $titleIndex = $intradayCount;
            }
            $wasteNumber = 'WS' . date('ymd') . $titleIndex;


            $tmpInsertRow = [
                'waste_number' => $wasteNumber,
                'waste_ids' => implode(',',$wasteIds),
                'total_number' => $wasterSellList['total_number'],
                'total_price' => $wasterSellList['total_price'],
                'waste_buyer_id' => $wasteBuyerId,
                'company_id' => $userInfo['company_id'],
            ];

            $wasteSellObj->fill($tmpInsertRow);
            $wasteSellObj->save();

            $wasterSellId = $wasteSellObj->id;

            //卖出详情处理
            foreach ($wasterSellList['list'] as $wasterSellRow){
                $wasteId = $wasterSellRow['waste_id'];
                $sellNum = $wasterSellRow['number'];
                $sellPrice = $wasterSellRow['price'];

                //保存记录
                $wasteSellDetailObj = \App\Eloquent\Ygt\WasteSellDetail::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'waste_sell_id' => $wasterSellId,
                    'waste_id' => $wasteId,
                    'number' => $sellNum,
                    'price' => $sellPrice,
                ];

                $wasteSellDetailObj->fill($tmpInsertRow);
                $wasteSellDetailObj->save();

                //废品库存数据处理
                $wasterRow = \App\Eloquent\Ygt\Waste::where(['id'=>$wasteId])->first();
                $wasterRow->number = $wasterRow->number - $sellNum;
                $wasterRow->total_seller_number = $wasterRow->total_seller_number + $sellNum;
                $wasterRow->save();

                //废品流水处理
                $wasteWaterObj = \App\Eloquent\Ygt\WasteWater::firstOrNew(['id'=>'']);
                $tmpInsertRow = [
                    'waste_id' => $wasteId,
                    'type' => 2,//2-卖出废品
                    'relate_id' => $wasterSellId,
                    'number' => $sellNum,
                    'residual_number' => $wasterRow->number,
//                    'unit' => $unit,
                    'company_id' => $userInfo['company_id'],
                    'uid' => $userId,
                ];

                $wasteWaterObj->fill($tmpInsertRow);
                $wasteWaterObj->save();
            }

            //卖出账单处理
            $payType = '';
            $wasteBuyerRow = \App\Eloquent\Ygt\WasteBuyer::where(['id'=>$wasteBuyerId])->first();
            if($wasteBuyerRow){
                $payType = $wasteBuyerRow->pay_type;
            }

            $wasteBillObj = \App\Eloquent\Ygt\WasteBill::firstOrNew(['id'=>'']);

            ////生成废品卖出记录编号
            $snNumber = '';
            //获取是当天的第几单
            $dayStartTime = strtotime(date('Ymd'));
            $intradayCount = \App\Eloquent\Ygt\WasteBill::withTrashed()->where([['created_at', '>=', $dayStartTime]])->get()->count();
            $titleIndex = '';
            $intradayCount++;
            if ($intradayCount < 10) {
                $titleIndex = sprintf('0%d', $intradayCount);
            } else {
                $titleIndex = $intradayCount;
            }
            $snNumber = 'WB' . date('ymd') . $titleIndex;

            $tmpInsertRow = [
                'waste_buyer_id' => $wasteBuyerId,
                'sn' => $snNumber,
                'total_money' => $wasterSellList['total_price'],
                'now_money' => $wasterSellList['total_price'],
                'pay_type' => $payType,
                'add_user_id' => $userId,
                'company_id' => $userInfo['company_id'],
            ];

            $wasteBillObj->fill($tmpInsertRow);
            $wasteBillObj->save();
        }

        ////发送消息给収品单位
        //获取収品单位的userId
        $wasteBuyerRow = \App\Eloquent\Ygt\WasteBuyer::where(['id'=>$wasteBuyerId])->first();
        if($wasteBuyerRow){
            $sendUserId = $wasteBuyerRow['user_id'];

            $messageData = [
                'company_id' => 2,
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $sendUserId,
                'foreign_key' => 0,
                'type' => 35,
                'type_id' => $wasterSellId,
                'title' => '收到新的废料',
                'content' => '收到新的废料',
                'type_status' => 1,
            ];
            \App\Eloquent\Ygt\UserMessage::sendWorkFlowMessage($messageData);
        }


        return '操作成功';
    }

    //卖废品时获取废品详情
    public function getWasteInfo()
    {
        $wasteIds = request('waste_ids');
        $wasteIdArr = [];
        if($wasteIds){
            $wasteIdArr = explode(',',$wasteIds);
        }

        $wasteList = [];
        foreach ($wasteIdArr as $wasteId){
            if($wasteId){
                //判断废品类型
                $wasteRow = \App\Eloquent\Ygt\Waste::where(['id'=>$wasteId])->first();
                if(!$wasteRow){
                    continue;
                }

                if($wasteRow['relate_type'] == 1){//材料
                    //获取材料信息
                    $materialRow = \App\Eloquent\Ygt\Product::where(['id'=>$wasteRow['relate_id']])->first();
                    if(!$materialRow){
                        continue;
                    }

                    //数量使用废品的
                    $materialRow['number'] = $wasteRow['number'];

                    //追加材料自定义属性
                    $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
                    $where = ['product_id' => $materialRow['id']];
                    $productFields = $ProductFieldsModel->getData($where,'','','',['id','asc']);
                    $productFields = $productFields->map(function ($item) {
                        $data['field_name'] = $item->field_name;
                        $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);

                        $data['field_value'] = $item->$comumnName.$item['unit'];
                        return $data;
                    });


                    $fieldsList         = $productFields;
                    $firstText = $secondText = $thirdText ='';
                    if(!empty($fieldsList))
                    {
                        if(isset($fieldsList[0]))
                        {
                            $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                        }
                        if(isset($fieldsList[1]))
                        {
                            $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                        }
                        if(isset($fieldsList[2]))
                        {
                            $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                        }
                    }
                    $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
                    $materialRow['custom_fields']        = $fieldsList;
                    $materialRow['first_text']           = $firstText;
                    $materialRow['second_text']          = $secondText;
                    $materialRow['third_text']           = $thirdText;
                    $materialRow['custom_fields_text']   = $customFieldsText;
                    $materialRow['custom_fields'] = $productFields;

                    //添加废品ID
                    $materialRow['waste_id'] = $wasteId;

                    //追加材料图片地址
                    $materialRow['img_url'] = '';
                    if ($materialRow['img_id']) {
                        $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                    }

                    //按供应商分类
                    if(!$materialRow['seller_company_id']){
                        $materialRow['seller_company_id'] = 0;//本厂材料
                    }


                    if(!isset($wasteList[$materialRow['seller_company_id']])){
                        if($materialRow['seller_company_id'] == 0){
                            $wasteList[$materialRow['seller_company_id']]['supllier_name'] = '材料废品';
                            $wasteList[$materialRow['seller_company_id']]['pay_method'] = '无';
                            $wasteList[$materialRow['seller_company_id']]['supllier_id'] = 0;
                        }else{
                            //获取供应商信息
                            $supllierRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$materialRow['seller_company_id']])->first();
                            if($supllierRow){
                                $wasteList[$materialRow['seller_company_id']]['supllier_name'] = $supllierRow['title'];
                                $wasteList[$materialRow['seller_company_id']]['pay_method'] = $supllierRow['pay_type'];
                                $wasteList[$materialRow['seller_company_id']]['supllier_id'] = $materialRow['seller_company_id'];
                            }else{
                                $wasteList[$materialRow['seller_company_id']]['supllier_name'] = '未知供应商';
                                $wasteList[$materialRow['seller_company_id']]['pay_method'] = '无';
                                $wasteList[$materialRow['seller_company_id']]['supllier_id'] = $materialRow['seller_company_id'];
                            }
                        }
                    }

                    //添加材料信息
                    $wasteList[$materialRow['seller_company_id']]['material_list'][] = $materialRow;
                }else{//工序废品
                    if(!isset($wasteList['-1'])){
                        $wasteList['-1']['supllier_name'] = '工序废品';
                        $wasteList['-1']['pay_method'] = '无';
                        $wasteList['-1']['supllier_id'] = -1;
                    }

                    //废品信息处理
                    $wasteName = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$wasteRow['relate_id']])->first();
                    if($wasteName){
                        $wasteName = $wasteName->title;
                    }else{
                        //获取软删除数据
                        $processWasteTitle = \App\Eloquent\Ygt\OrdertypeProcessWaste::withTrashed()->where(['id'=>$wasteRow['relate_id']])->first();
                        if($processWasteTitle){
                            $wasteName = $processWasteTitle->title.'【已删除】';
                        }else{
                            $wasteName = '';
                        }
                    }


                    $materialRow = [
                        'waste_id' => $wasteId,
                        'product_name' => $wasteName,
                        'unit' => 'kg',
                        'img_url' => '',
                        'first_text' => '',
                        'second_text' => '',
                        'third_text' => '',
                        'custom_fields_text' => '',
                        'number' => $wasteRow['number'],
                    ];

                    $wasteList['-1']['material_list'][] = $materialRow;
                }

            }
        }

        $wasteList = array_values($wasteList);
        return $wasteList;
    }


    //废品卖出记录（収品单位収品记录）
    public function getWasteSellList(){
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $wasteBuyerId = request('waste_buyer_id');
        $companyId = request('company_id');

        if(!$companyId){
            $companyId = $userInfo['company_id'];
        }

        if(!$wasteBuyerId){
            //获取userId对应的収品单位ID
            $wasteBuyerRow = \App\Eloquent\Ygt\WasteBuyer::where(['user_id'=>$userId])->first();
            if(!$wasteBuyerRow){
                return [
                    'code' => 1,
                    'message' => '用户信息异常'
                ];
            }

            $wasteBuyerId = $wasteBuyerRow['id'];
        }



        $where = [];
        $where[] = ['company_id','=',$companyId];

        if($wasteBuyerId){
            $where[] = ['waste_buyer_id','=',$wasteBuyerId];
        }


        $wasterSellList = \App\Eloquent\Ygt\WasteSell::where($where)->orderBy('id','desc')->get();

        //获取废品名称
        $wasterSellList->transform(function ($item, $key) {
            $wasteIds = $item['waste_ids'];
            $wasteIdsArr = explode(',',$wasteIds);
            foreach ($wasteIdsArr as $wasteId){
                if($wasteId){
                    $wasteName = \App\Engine\Waste::getWasteName($wasteId);
                    $item['title'].=$wasteName.",";
                }
            }
            $item['title'] = trim($item['title'],',');

            //修改时间
            $tmpArr = $item->toArray();
            $item['time'] = date('Y-m-d',$tmpArr['updated_at']);

            return $item;
        });

        return $wasterSellList;
    }

    //収品单位查看废品记录详情
    public function getWasteDetail(){
        $wasteSellId = request('waste_sell_id');

        $wasteSellDetailList = \App\Eloquent\Ygt\WasteSellDetail::where(['waste_sell_id'=>$wasteSellId])->get();

        $materialWasteList = $processWasteList = [];
        $materialWasteList['title'] = '材料废品';
        $materialWasteList['data'] = [];
        $processWasteList['title'] = '工序废品';
        $processWasteList['data'] = [];

        foreach ($wasteSellDetailList as $wasteSellDetailRow){
            $wasteId = $wasteSellDetailRow['waste_id'];
            $wasteRow = \App\Eloquent\Ygt\Waste::where(['id'=>$wasteId])->first();

            $relateType = $wasteRow['relate_type'];


            if($relateType == 1){//材料废品

                //获取材料信息
                $materialId = $wasteRow['relate_id'];
                //获取材料信息
                $materialRowPre = \App\Eloquent\Ygt\Product::where(['id'=>$materialId])->first();
                if(!$materialRowPre){
                    continue;
                }

                $materialRow['id'] = $materialRowPre['id'];
                $materialRow['img_id'] = $materialRowPre['img_id'];
                $materialRow['seller_company_id'] = $materialRowPre['seller_company_id'];
                $materialRow['unit'] = $materialRowPre['unit'];
                $materialRow['product_name'] = $materialRowPre['product_name'];


                //追加材料自定义属性
                $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
                $where = ['product_id' => $materialRow['id']];
                $productFields = $ProductFieldsModel->getData($where,'','','',['id','asc']);
                $productFields = $productFields->map(function ($item) {
                    $data['field_name'] = $item->field_name;
                    $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);

                    $data['field_value'] = $item->$comumnName.$item['unit'];
                    return $data;
                });


                $fieldsList         = $productFields;
                $firstText = $secondText = $thirdText ='';
                if(!empty($fieldsList))
                {
                    if(isset($fieldsList[0]))
                    {
                        $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                    }
                    if(isset($fieldsList[1]))
                    {
                        $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                    }
                    if(isset($fieldsList[2]))
                    {
                        $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                    }
                }
                $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;
                $materialRow['custom_fields']        = $fieldsList;
                $materialRow['first_text']           = $firstText;
                $materialRow['second_text']          = $secondText;
                $materialRow['third_text']           = $thirdText;
                $materialRow['custom_fields_text']   = $customFieldsText;
                $materialRow['custom_fields'] = $productFields;

                //追加材料图片地址
                $materialRow['img_url'] = '';
                if ($materialRow['img_id']) {
                    $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
                }

                //供应商
                if(!$materialRow['seller_company_id']){
                    $materialRow['supllier_name'] = '材料废品';
                }else{
                    $supllierRow = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$materialRow['seller_company_id']])->first();
                    if($supllierRow){
                        $materialRow['supllier_name'] = "供应商：".$supllierRow['title'];
                    }else{
                        $materialRow['supllier_name'] = '未知供应商';
                    }
                }

                //废品数量
                $materialRow['waste_num'] = $wasteSellDetailRow['number'].$materialRow['unit'];

                $materialWasteList['data'][] = $materialRow;

            }elseif($relateType == 2){//工序废品

                $processRow = [];
                //获取工序废品信息--废品名称
                $processWasteTitle = \App\Eloquent\Ygt\OrdertypeProcessWaste::where(['id'=>$wasteRow['relate_id']])->first();
                if($processWasteTitle){
                    $processWasteTitle = $processWasteTitle->title;
                }else{
                    //获取软删除数据
                    $processWasteTitle = \App\Eloquent\Ygt\OrdertypeProcessWaste::withTrashed()->where(['id'=>$wasteRow['relate_id']])->first();
                    if($processWasteTitle){
                        $processWasteTitle = $processWasteTitle->title.'【已删除】';;
                    }else{
                        $processWasteTitle = '';
                    }
                }

                $processRow['id'] = $wasteRow['relate_id'];
                $processRow['title'] = $processWasteTitle;
                $processRow['waste_num'] = $wasteSellDetailRow['number'].'kg';

                $processWasteList['data'][] = $processRow;
            }
        }

        $detailList = [];
        if(!empty($materialWasteList)){
            $detailList[] = $materialWasteList;
        }

        $re = [
            'material_waste_list' => $materialWasteList,//材料废品列表
            'process_waste_list' => $processWasteList,//工序废品列表

        ];//接口返回的值

        return $re;


    }

}